import $ from '../common'

class $page {
	constructor(name = "list") {
		this.version = '1.00.00'
		this.onReachEnd = false
		this.limit = 9999
		this.page = 1
		this.list = []
		this.listName = name
		this._option = {}
		this.$loading = ""
	}

	get(option) {
		let {
			url,
			param = {},
			dataMap,
			status
		} = option
		this._option = option
		param.limit = this.limit
		param.page = 1 || this.page
		if(this.$loading) {
			return false;
		}
		this.$loading = true
		$.self().setData({
			$loading: this.$loading
		})
		$.get(url, param, (data = []) => {
			let list = data.map((v) => {
				dataMap && [v = dataMap(v)]
				v.page = this.page
				return v
			})
			if(this.page == 1) {
				this.list = list
			} else {
				this.list = this.list.concat(list)
			}
			if(status == "onReach" && data.length > 0) {
				if(data.length < this.limit) {
					this.onReachEnd = true
				} else {
					this.page++
				}
			}
			if(this.page > 1 && data.length == 0) {
				this.onReachEnd = true
			}
			this.$loading = false
			$.self().setData({
				[this.listName]: this.list || [],
				onReachEnd: this.onReachEnd,
				$loading: this.$loading
			})
		}, () => {
			this.$loading = false
			$.self().setData({
				$loading: this.$loading
			})
		})
	}

	setCurrent(index, id, page) {
		this.current = {
			id,
			index,
			page
		}
	}

	getCurrent(key = "uuid", ext) {
		let $current = this.current || {}
		let {
			url,
			param = {}
		} = this._option
		param.page = $current.page || 1
		$current.id && $.get(url, param, (data = []) => {
			for(let k in data) {
				let v = data[k]
				if(v[key] == $current.id) {
					ext && [v = ext(v)]
					v.page = $current.page
					this.list[$current.index] = v
					$.self().setData({
						[this.listName]: this.list || []
					})
					break
				}
			}
		})
	}

	remove(index) {
		this.list = $.setDelete(this.list, index)
		this.list = this.list.map((v, k) => {
			v.page = parseInt(k / this.limit) + 1
			return v
		})
		$.self().setData({
			[this.listName]: this.list || []
		})
	}

	pullDownRefresh() {
		this.page = 1
		this.onReachEnd = false
		this._option.status = "onPull"
		this.get(this._option)
	}

	reachBottom() {
		if(!this.onReachEnd) {
			if(this.page == 1) {
				//this.page = 2
			}
			//this._option.status = "onReach"
			//this.get(this._option)
		}
	}

}

export default $page